"""
浏览器管理器
"""

from datetime import datetime
from itertools import count
from typing import Dict, List, Optional, Any

from models.api_models import BrowserInfo


class BrowserManager:
    """浏览器管理器"""
    
    def __init__(self):
        self.browsers: Dict[str, Dict[str, Any]] = {}
        self.browser_counter = count()
    
    async def create_browser(self, 
                           name: Optional[str] = None, 
                           proxy_url: Optional[str] = None,
                           headless: bool = True) -> str:
        """创建新的浏览器实例"""
        from playwright.async_api import async_playwright
        
        browser_id = f"browser_{next(self.browser_counter)}"
        browser_name = name or f"Browser-{browser_id}"
        
        # 启动Playwright
        playwright = await async_playwright().start()
        
        # 配置启动选项
        launch_options = {"headless": headless}
        if proxy_url:
            # 解析代理URL
            if proxy_url.startswith("http://"):
                proxy_parts = proxy_url[7:].split("@")
                if len(proxy_parts) == 2:
                    auth, server = proxy_parts
                    username, password = auth.split(":")
                    launch_options["proxy"] = {
                        "server": f"http://{server}",
                        "username": username,
                        "password": password
                    }
                else:
                    launch_options["proxy"] = {"server": proxy_url}
        
        browser = await playwright.chromium.launch(**launch_options)
        context = await browser.new_context()
        
        self.browsers[browser_id] = {
            "id": browser_id,
            "name": browser_name,
            "playwright": playwright,
            "browser": browser,
            "context": context,
            "created_at": datetime.now(),
            "last_used": None,
            "proxy_url": proxy_url,
            "is_active": True
        }
        
        return browser_id
    
    def get_browser(self, browser_id: str) -> Optional[Dict[str, Any]]:
        """获取浏览器实例"""
        return self.browsers.get(browser_id)
    
    def get_all_browsers(self) -> List[BrowserInfo]:
        """获取所有浏览器信息"""
        return [self._browser_to_info(browser) for browser in self.browsers.values()]
    
    async def close_browser(self, browser_id: str) -> bool:
        """关闭浏览器"""
        if browser_id in self.browsers:
            browser_data = self.browsers[browser_id]
            try:
                await browser_data["context"].close()
                await browser_data["browser"].close()
                await browser_data["playwright"].stop()
                browser_data["is_active"] = False
            except Exception as e:
                print(f"关闭浏览器失败: {e}")
            
            del self.browsers[browser_id]
            return True
        return False
    
    async def cleanup_all_browsers(self):
        """清理所有浏览器"""
        browser_ids = list(self.browsers.keys())
        for browser_id in browser_ids:
            await self.close_browser(browser_id)
    
    def _browser_to_info(self, browser_data: Dict[str, Any]) -> BrowserInfo:
        """将浏览器数据转换为BrowserInfo"""
        return BrowserInfo(
            id=browser_data["id"],
            name=browser_data["name"],
            created_at=browser_data["created_at"],
            is_active=browser_data["is_active"],
            last_used=browser_data["last_used"],
            page_count=len(browser_data["context"].pages) if browser_data.get("context") else 0,
            proxy_url=browser_data.get("proxy_url")
        ) 